package com.duruikang.LeaveAPI.api;

import cn.hutool.core.util.NumberUtil;
import com.duruikang.LeaveAPI.common.http.ResponseResult;
import com.duruikang.LeaveAPI.common.sercurity.utils.JwtTokenUtil;
import com.duruikang.LeaveAPI.entity.Leaving;
import com.duruikang.LeaveAPI.entity.Sort;
import com.duruikang.LeaveAPI.entity.Student;
import com.duruikang.LeaveAPI.form.ExamineDetailForm;
import com.duruikang.LeaveAPI.form.LeavingDetailForm;
import com.duruikang.LeaveAPI.form.LeavingForm;
import com.duruikang.LeaveAPI.form.TokenForm;
import com.duruikang.LeaveAPI.service.LeavingService;
import com.duruikang.LeaveAPI.service.SortService;
import com.duruikang.LeaveAPI.service.impl.ExamineServiceImpl;
import com.duruikang.LeaveAPI.service.impl.SecurityServiceImpl;
import com.duruikang.LeaveAPI.service.impl.StudentInformationServiceImpl;
import com.duruikang.LeaveAPI.service.impl.TeacherInformationServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 提交请假单
 * 获取请假单列表
 * 获取请假单详情
 *
 * @author szh Drik
 */
@CrossOrigin
@RestController
@RequestMapping("/api")
public class LeavingApi {

    @Autowired
    private SortService sortService;

    @Autowired
    private StudentInformationServiceImpl studentService;

    @Autowired
    private TeacherInformationServiceImpl teacherService;

    @Autowired
    private SecurityServiceImpl securityService;

    @Autowired
    private LeavingService leavingService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    Environment environment;

    @Autowired
    private ExamineServiceImpl examineService;

    /**
     * 处理传来的请假单信息，保存至数据库
     *
     * @param form 包含请假单内容的信息
     * @return 是否成功
     */
    @PostMapping("/askforleave")
    public ResponseResult<Boolean> askForLeave(@RequestBody @Valid LeavingForm form) {
        //登录检查
        String checkResult = securityService.checkToken(form.getToken());
        if(checkResult!=null){
            return ResponseResult.getErrorResult(checkResult);
        }
        //从token中获取用户id，同时检查token是否过期
        String id = null;
        try {
            id = jwtTokenUtil.getUsername(form.getToken());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(id ==null){
            return ResponseResult.getMessageResult(false, "E-UserTimeout");
        }
        //从student表中查询学生信息
        Student student = studentService.query().eq("account_id", id).one();
        //获取请假事由，转换为列要求的int
        int reason = sortService.getSortByName(form.getLeavingReason()).getId();
        //计算请假时间，计算并转回为列要求的int
        int type = 0;
        long days = ChronoUnit.DAYS.between(form.getLeavingStart(),form.getLeavingEnd());
        //从配置文件读取请假等级所在分组
        String typeSetting = environment.getProperty("leaving.type");
        if(typeSetting==null){
            return ResponseResult.getMessageResult(false, "E-MissingSettings");
        }
        List<Sort> levels = sortService.getLevelList(Integer.parseInt(typeSetting));
        //找到最高等级
        for (Sort s : levels) {
            if (NumberUtil.isGreaterOrEqual(new BigDecimal(days), s.getValue())) {
                type = s.getId();
                break;
            }
        }
        //调用service
        boolean res = leavingService.submitLeaving(student.getStudentId(), reason, type, form.getLeavingDestination(), form.getLeavingDetail(),
                form.getLeavingStart(), form.getLeavingEnd());

        if(res){
            return ResponseResult.getSuccessResult(res);
        }else{
            return ResponseResult.getErrorResult("E-Database");
        }
    }

    @PostMapping("/getleavings")
    public ResponseResult<List<Map<String, String>>> getLeavings(@RequestBody @Valid TokenForm form) {
        String checkResult = securityService.checkToken(form.getToken());
        if(checkResult!=null){
            return ResponseResult.getErrorResult(checkResult);
        }
        //从token中获取用户id
        String id = jwtTokenUtil.getUsername(form.getToken());
        return ResponseResult.getSuccessResult(leavingService.getAllLeavings(id));
    }

    @PostMapping("/getleavingdetail")
    public ResponseResult<List<Map<String,String>>> getLeavingDetail(@RequestBody @Valid LeavingDetailForm form){
        String checkResult = securityService.checkToken(form.getToken());
        if(checkResult!=null){
            return ResponseResult.getErrorResult(checkResult);
        }
        String id = jwtTokenUtil.getUsername(form.getToken());
        List<Map<String,String>> res = new ArrayList<>();
        res.add(studentService.getStudent(id));
        res.add(leavingService.getLeaving(form.getLeavingId()));
        res.addAll(examineService.getExamines(form.getLeavingId()));
        return ResponseResult.getSuccessResult(res);
    }

    @PostMapping("/getexaminingleavings")
    public ResponseResult<List<Map<String, String>>> getExaminingLeavings(@RequestBody @Valid TokenForm form) {
        String checkResult = securityService.checkToken(form.getToken());
        if(checkResult!=null){
            return ResponseResult.getErrorResult(checkResult);
        }
        //从token中获取用户id
        String id = jwtTokenUtil.getUsername(form.getToken());
        return ResponseResult.getSuccessResult(leavingService.getExaminingLeavings(id));
    }

    @PostMapping("/getexaminingdetail")
    public ResponseResult<List<Map<String, String>>> getExaminingDetail(@RequestBody @Valid ExamineDetailForm form) {
        String checkResult = securityService.checkToken(form.getToken());
        if(checkResult!=null){
            return ResponseResult.getErrorResult(checkResult);
        }
        String id = jwtTokenUtil.getUsername(form.getToken());
        List<Map<String,String>> res = new ArrayList<>();
        Leaving leaving = leavingService.query().eq("leaving_id",form.getLeavingId()).one();
        Student student = studentService.query().eq("student_id",leaving.getStudentId()).one();
        res.add(studentService.getStudent(student.getAccountId()));
        res.add(leavingService.getLeaving(form.getLeavingId()));
        res.addAll(examineService.getExamines(form.getLeavingId()));
        return ResponseResult.getSuccessResult(res);
    }

}
